import { defineStore } from 'pinia'
import { io } from 'socket.io-client'
import { useAuthStore } from './auth'

/**
 * WebSocket Store
 * 提供WebSocket连接管理和事件处理功能
 */
export const useSocketStore = defineStore('socket', {
  state: () => ({
    // WebSocket连接实例
    socket: null,
    // 连接状态
    connected: false,
    // 事件监听器映射
    listeners: new Map(),
    // 待发送事件队列
    eventQueue: []
  }),

  getters: {
    // 获取连接状态
    isConnected: (state) => state.connected
  },

  actions: {
    /**
     * 初始化WebSocket连接
     */
    init() {
      // 如果已经有连接，先断开
      if (this.socket) {
        this.socket.disconnect()
      }
      
      // 创建新的socket连接
      this.socket = io(import.meta.env.VITE_WS_URL || 'http://localhost:8002', {
        autoConnect: true,
        reconnection: true,
        reconnectionDelay: 1000,
        reconnectionAttempts: 5
      })
      
      if (this.socket) {
        this.connected = this.socket.connected
        
        // 监听连接状态变化
        this.socket.on('connect', () => {
          this.connected = true
          console.log('WebSocket连接已建立')
          
          // 发送认证事件加入authenticated房间
          const authStore = useAuthStore()
          if (authStore.token) {
            this.socket.emit('authenticate', authStore.token)
            console.log('已发送WebSocket认证请求')
          }
          
          // 初始化所有store的WebSocket监听器
          this.initAllStoreListeners()
          
          // 连接成功后发送队列中的事件
          this.processEventQueue()
        })
        
        this.socket.on('disconnect', () => {
          this.connected = false
          console.log('WebSocket连接已断开')
        })
        
        this.socket.on('connect_error', (error) => {
          console.error('WebSocket连接错误:', error)
        })
        
        // 如果已经连接，立即处理队列
        if (this.connected) {
          this.initAllStoreListeners()
          this.processEventQueue()
        }
      }
    },

    /**
     * 初始化所有store的WebSocket监听器
     */
    initAllStoreListeners() {
      try {
        // 添加全局定期状态更新监听器
        this.socket.on('student-status-updated', (data) => {
          if (data.type === 'periodic_update') {
            console.log('📡 收到定期状态更新，更新所有相关store')
            
            // 通知所有相关store更新数据
            import('./students.js').then(({ useStudentsStore }) => {
              const studentsStore = useStudentsStore()
              studentsStore.handlePeriodicUpdate(data.data)
            })
            
            import('./afterSchool.js').then(({ useAfterSchoolStore }) => {
              const afterSchoolStore = useAfterSchoolStore()
              if (afterSchoolStore.handlePeriodicUpdate) {
                afterSchoolStore.handlePeriodicUpdate(data.data)
              }
            })
          }
        })
        
        // 动态导入stores以避免循环依赖
        import('./students.js').then(({ useStudentsStore }) => {
          const studentsStore = useStudentsStore()
          studentsStore.initSocketListeners()
        })
        
        import('./afterSchool.js').then(({ useAfterSchoolStore }) => {
          const afterSchoolStore = useAfterSchoolStore()
          afterSchoolStore.initSocketListeners()
        })
        
        import('./exceptions.js').then(({ useExceptionsStore }) => {
          const exceptionsStore = useExceptionsStore()
          exceptionsStore.initSocketListeners()
        })
        
        console.log('所有store的WebSocket监听器已初始化')
      } catch (error) {
        console.error('初始化store监听器失败:', error)
      }
    },

    /**
     * 发送WebSocket事件
     * @param {string} event - 事件名称
     * @param {any} data - 发送的数据
     */
    emit(event, data) {
      if (this.socket && this.connected) {
        this.socket.emit(event, data)
      } else {
        // 将事件添加到队列中，等待连接建立后发送
        this.eventQueue.push({ event, data })
        console.log(`WebSocket未连接，事件 ${event} 已加入队列`)
      }
    },

    /**
     * 监听WebSocket事件
     * @param {string} event - 事件名称
     * @param {Function} callback - 回调函数
     */
    on(event, callback) {
      if (this.socket) {
        this.socket.on(event, callback)
        
        // 记录监听器，便于清理
        if (!this.listeners.has(event)) {
          this.listeners.set(event, [])
        }
        this.listeners.get(event).push(callback)
      }
    },

    /**
     * 移除WebSocket事件监听
     * @param {string} event - 事件名称
     * @param {Function} callback - 回调函数（可选）
     */
    off(event, callback) {
      if (this.socket) {
        if (callback) {
          this.socket.off(event, callback)
          
          // 从监听器映射中移除
          const eventListeners = this.listeners.get(event)
          if (eventListeners) {
            const index = eventListeners.indexOf(callback)
            if (index > -1) {
              eventListeners.splice(index, 1)
            }
          }
        } else {
          this.socket.off(event)
          this.listeners.delete(event)
        }
      }
    },

    /**
     * 处理事件队列
     */
    processEventQueue() {
      while (this.eventQueue.length > 0 && this.connected) {
        const { event, data } = this.eventQueue.shift()
        this.socket.emit(event, data)
        console.log(`发送队列中的事件: ${event}`)
      }
    },

    /**
     * 断开WebSocket连接
     */
    disconnect() {
      if (this.socket) {
        this.socket.disconnect()
        this.socket = null
        this.connected = false
      }
    },

    /**
     * 清理所有事件监听器并断开连接
     */
    cleanup() {
      if (this.socket) {
        this.listeners.forEach((callbacks, event) => {
          callbacks.forEach(callback => {
            this.socket.off(event, callback)
          })
        })
        this.listeners.clear()
        this.socket.disconnect()
        this.socket = null
        this.connected = false
      }
      // 清空事件队列
      this.eventQueue = []
    }
  }
})